/*
 * 程序清单：这是一个 PWM 设备使用例程
 * 例程导出了 pwm_led_sample 命令到控制终端
 * 命令调用格式：pwm_led_sample
 * 程序功能：通过 PWM 设备控制 LED 灯的亮度，可以看到LED不停的由暗变到亮，然后又从亮变到暗。
*/

#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>

#define PWM_DEV_NAME        "pwm3"  /* PWM设备名称 */
#define PWM_DEV_CHANNEL     1       /* PWM通道 */

struct rt_device_pwm *pwm_dev;      /* PWM设备句柄 */

#define TMC_ENN_PIN               GET_PIN(A, 4)
#define TMC_DIR_PIN               GET_PIN(A, 5)


static int pwm_sample(void)
{
    rt_uint32_t period, pulse, dir;

    /* 范围为1 KHZ ~ 50KHZ */
    /* 1000000 ~ 2000 */

    rt_uint32_t max = 1000000, min = 2000;
    rt_uint32_t step = 100;

    int direction = -1;
    rt_uint32_t current = 1000000;

    rt_pin_mode(TMC_DIR_PIN, PIN_MODE_OUTPUT);
    rt_pin_mode(TMC_ENN_PIN, PIN_MODE_OUTPUT);

    rt_pin_write(TMC_DIR_PIN, PIN_HIGH);
    rt_pin_write(TMC_ENN_PIN, PIN_LOW);
    rt_thread_mdelay(500);

    /* 查找设备 */
    pwm_dev = (struct rt_device_pwm *)rt_device_find(PWM_DEV_NAME);
    if (pwm_dev == RT_NULL)
    {
        rt_kprintf("pwm sample run failed! can't find %s device!\n", PWM_DEV_NAME);
        return RT_ERROR;
    }

    /* 设置PWM周期和脉冲宽度默认值 */
    rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, current, current >> 1);
    /* 使能设备 */
    rt_pwm_enable(pwm_dev, PWM_DEV_CHANNEL);

    while (1)
    {
        rt_thread_mdelay(50);

        current += step * direction;

        if (current >= max) {
            direction = -1;
        } else if (current <= min) {
            direction = 1;
        }

        /* 设置PWM周期和脉冲宽度 */
        rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, current, current >> 1);
    }
}
INIT_APP_EXPORT(pwm_sample);
